package com.znufe.exam.controller.admin;


import com.github.pagehelper.PageInfo;
import com.znufe.exam.base.BaseApiController;
import com.znufe.exam.base.RestResponse;
import com.znufe.exam.domain.grade.ExamInfoOfCourseOfClassResponseObject;
import com.znufe.exam.domain.grade.ExamQuestionScoreSituationObject;
import com.znufe.exam.domain.grade.StudentExamDetailRequestObject;
import com.znufe.exam.domain.grade.StudentExamQuestionAnswerObject;
import com.znufe.exam.service.ExamGradeService;
import com.znufe.exam.service.ExamPaperService;
import com.znufe.exam.utility.PageInfoHelper;
import com.znufe.exam.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.znufe.exam.viewmodel.admin.grade.*;
import com.znufe.exam.viewmodel.admin.question.QuestionEditRequestVM;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Api(description = "查询成绩",value="查询成绩" )
@RestController("AdminExamGradeController")
@RequestMapping(value="api/admin/grade")
public class ExamGradeController extends BaseApiController {

    @Autowired
    private final ExamGradeService examGradeService;
    @Autowired
    private final ExamPaperService examPaperService;

    public ExamGradeController(ExamGradeService examGradeService, ExamPaperService examPaperService) {
        this.examGradeService = examGradeService;
        this.examPaperService = examPaperService;
    }

    @RequestMapping(value = "/get_class_course_content", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过班级id获得班级课程及课程下的试卷（按班级id查找）",
            notes = "获取某个班所上课程及课程下的试卷[多张视图]，作者：lin keqing")
    public RestResponse<CourseContentOfClassResponseVM> getClassCourseContent(@RequestBody ClassGradeRequestVM model) {
        if (null == model.getClassId()) {
            return new RestResponse<>(2,"班级id不能为空！");
        }
        CourseContentOfClassResponseVM responseVM = examGradeService
                .getCourseContentByClassId(model.getClassId());
        return RestResponse.ok(responseVM);
    }

    @RequestMapping(value = "/get_class_course_grade_rank", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过班级id、课程id获得某个班级某个课程的学生成绩排名（按班级id、课程id查找）",
            notes = "获取某个班所上课程的成绩排名[class_student_course_grade_info]，作者：lin keqing")
    public RestResponse<List<ClassCourseGradeResponseVM>> getClassCourseGradeRank(@RequestBody ClassCourseGradeRequestVM model) {
        if (null == model.getClassId() || null == model.getCourseId()) {
            return new RestResponse<>(2,"班级id与课程id均不能为空！");
        }
        List<ClassCourseGradeResponseVM> responseVM = examGradeService.selectClassCourseGrade(model);
        return RestResponse.ok(responseVM);
    }

    @RequestMapping(value = "/get_class_exam_grade_rank", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过班级id、试卷id获得某个班级某个试卷的学生成绩排名（按班级id、试卷id查找）",
            notes = "获取某个班的某场考试的成绩排名[student_exam_grade_info]，作者：lin keqing")
    public RestResponse<List<ClassExamGradeResponseVM>> getClassExamGradeRank(@RequestBody ClassExamGradeRequestVM model) {
        if (null == model.getClassId() || null == model.getExamPaperId()) {
            return new RestResponse<>(2,"班级id与试卷id均不能为空！");
        }
        List<ClassExamGradeResponseVM> responseVM = examGradeService.selectClassExamGrade(model);
        return RestResponse.ok(responseVM);
    }

    @RequestMapping(value = "/get_student_individual_grade", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过班级名称、学生名称获得某个学生的个人成绩（按班级名称、学生名称、课程名称查找）",
            notes = "获取某个学生的个人成绩[student_individual_grade_info]，作者：lin keqing")
    public RestResponse<List<StudentIndividualGradeResponseVM>> getStudentIndividualGrade(@RequestBody StudentIndividualGradeRequestVM model) {
        model = StudentIndividualGradeRequestVM.wipeBlank(model);
        List<StudentIndividualGradeResponseVM> responseVM = examGradeService.getStudentIndividualGradeInfo(model);
        return RestResponse.ok(responseVM);
    }

    @RequestMapping(value = "/get_student_exam_detail", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过学生id、试卷id获得某个学生的答卷详情（按学生id、试卷id查找）",
            notes = "获取某个学生生的某张试卷的答卷情况[t_exam_paper_question_customer_answer]，作者：lin keqing")
    public RestResponse<List<StudentExamDetailResponseVM>> getStudentExamDetail(@RequestBody StudentExamDetailRequestVM model) {
        ExamPaperEditRequestVM examPaperEditRequestVM = examPaperService.examPaperToVM(model.getExamPaperId());
        List<QuestionEditRequestVM> questionList = examPaperEditRequestVM.getTitleItems()
                .get(0).getQuestionItems();

        List<StudentExamDetailResponseVM> vmList = questionList.stream().map(q -> {
            StudentExamDetailResponseVM vm = modelMapper.map(q, StudentExamDetailResponseVM.class);
            vm.setQuestionId(q.getId());
            //System.out.println(vm.toString() + "     " +  vm.getQuestionId());
            return vm;
        }).collect(Collectors.toList());

        StudentExamDetailRequestObject obj = modelMapper.map(model, StudentExamDetailRequestObject.class);
        for (StudentExamDetailResponseVM vm : vmList) {
            obj.setQuestionId(vm.getQuestionId());
            StudentExamQuestionAnswerObject answer = examGradeService.selectStuAns(obj);
            if (answer == null) {
                vm.setStudentAnswer("学生未作答");
                vm.setStudentScore(0);
            } else {
                vm.setStudentAnswer(answer.getStuAnswer());
                vm.setStudentScore(answer.getStuScore());
            }
        }
        return RestResponse.ok(vmList);
    }

    @RequestMapping(value = "/get_class_all_exam_grade_rank", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过班级id获得某个班级所有试卷的学生成绩排名（按班级id查找）",
            notes = "获取某个班的所有考试的成绩排名[exam_paper_of_class、student_exam_grade_info]，作者：lin keqing")
    public RestResponse<List<ClassExamGradeResponseVM>> getAllExamGradeRankOfClass(@RequestBody ClassGradeRequestVM model) {
        List<Integer> examPaperIdsOfClass = examGradeService
                .selectExamPaperIdByClassId(model.getClassId());
        HashMap<Integer, String> examNameMap = (HashMap<Integer, String>) examGradeService.getExamPaperNameMap(examPaperIdsOfClass);
        List<ClassExamGradeResponseVM> vmList = new ArrayList<>();
        ClassExamGradeRequestVM requestVM = new ClassExamGradeRequestVM();
        requestVM.setClassId(model.getClassId());
        for (Integer examPaperId : examPaperIdsOfClass) {
            requestVM.setExamPaperId(examPaperId);
            List<ClassExamGradeResponseVM> rankOfExamPaper = examGradeService
                    .selectClassExamGrade(requestVM);
            for (ClassExamGradeResponseVM vm : rankOfExamPaper) {
                vm.setExamPaperName(examNameMap.get(vm.getExamPaperId()));
            }
            vmList.addAll(rankOfExamPaper);
        }
        return RestResponse.ok(vmList);
    }

    @RequestMapping(value = "/get_exam_info_of_course_of_class", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过班级id、课程id、试卷id获得某个班级下所有课程的所有试卷",
            notes = "获取某个班的所有试卷[course_class_info、course_exam_paper_info]，作者：lin keqing")
    public RestResponse<PageInfo<ExamInfoOfCourseOfClassResponseVM>> getAllExamInfoOfCourseOfClass(@RequestBody ExamInfoOfCourseOfClassRequestVM model) {
        PageInfo<ExamInfoOfCourseOfClassResponseObject> pageInfo =  examGradeService.selectExamInfoOfCourseOfClass(model);
        PageInfo<ExamInfoOfCourseOfClassResponseVM> page = PageInfoHelper.copyMap(pageInfo, d -> {
            ExamInfoOfCourseOfClassResponseVM vm = ExamInfoOfCourseOfClassResponseVM.from(d);
            return vm;
        });
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/get_exam_grade_distribution", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过班级id、试卷id获得试卷成绩的分数分布",
            notes = "获取某个班的某张试卷的成绩分布[class_vote_exam_grade_info]，作者：lin keqing")
    public RestResponse<ExamGradeDistributionResponseVM> getExamGradeDistribution(@RequestBody ExamGradeDistributionRequestVM model) {
        ExamGradeDistributionResponseVM vm = examGradeService.selectExamGradeDistribution(model);
        if (vm.getPerBelowSixty() == null) {
            return RestResponse.fail(2,"该班级还未进行此张试卷的考试，请进行考试后再查看统计！");
        }
        vm.setPerBelowSixty(vm.getPerBelowSixty() + "%");
        vm.setPerAboveSixtyBelowSeventy(vm.getPerAboveSixtyBelowSeventy() + "%");
        vm.setPerAboveSeventyBelowEighty(vm.getPerAboveSeventyBelowEighty() + "%");
        vm.setPerAboveEightyBelowNinety(vm.getPerAboveEightyBelowNinety() + "%");
        vm.setPerAboveNinety(vm.getPerAboveNinety() + "%");
        return RestResponse.ok(vm);
    }

    @RequestMapping(value = "/get_exam_question_score_situation", method = RequestMethod.POST, produces = "application/json")
    @ApiOperation(value = "通过班级id、试卷id获得某个班级答题情况统计",
            notes = "获取某个班的某张试卷的答题情况统计[t_exam_paper_question_customer_answer_view]，作者：lin keqing")
    public RestResponse<List<ExamQuestionScoreSituationResponseVM>> getExamQuestionScoreSituation(@RequestBody ExamGradeDistributionRequestVM model) {
        // 从答题表中取出所有的答题统计，并封装成一个HashMap
        List<ExamQuestionScoreSituationObject> objList = examGradeService.selectExamQusScoreSituation(model);
        if (objList.isEmpty()) {
            return RestResponse.fail(2,"该班级未进行此张试卷的考试！");
        }
        HashMap<Integer, ExamQuestionScoreSituationObject> toConvertMap = convertToMap(objList);

        ExamPaperEditRequestVM examPaperEditRequestVM = examPaperService.examPaperToVM(model.getExamPaperId());
        List<QuestionEditRequestVM> questionList = examPaperEditRequestVM.getTitleItems()
                .get(0).getQuestionItems();
        // 取出这张试卷所有的题目
        List<ExamQuestionScoreSituationResponseVM> vmList = questionList.stream().map(q -> {
            ExamQuestionScoreSituationResponseVM vm = modelMapper.map(q, ExamQuestionScoreSituationResponseVM.class);
            vm.setQuestionId(q.getId());
            return vm;
        }).collect(Collectors.toList());

        for (ExamQuestionScoreSituationResponseVM vm : vmList) {
            Integer qId = vm.getQuestionId();
            if (toConvertMap.containsKey(qId)) {
                ExamQuestionScoreSituationObject obj = toConvertMap.get(qId);
                vm.setClassId(model.getClassId());
                vm.setAnswerCount(obj.getAnswerCount());
                vm.setDoRightCount(obj.getDoRightCount());
                vm.setDoFalseCount(obj.getDoFalseCount());
                vm.setPerOfDoRight(obj.getPerOfDoRight() + "%");
            } else {
                vm.setClassId(model.getClassId());
                vm.setAnswerCount(0);
                vm.setDoRightCount(0);
                vm.setDoFalseCount(0);
                vm.setPerOfDoRight("0.0%");
            }
        }
        return RestResponse.ok(vmList);
    }

    private HashMap<Integer, ExamQuestionScoreSituationObject> convertToMap(List<ExamQuestionScoreSituationObject> objList) {
        HashMap<Integer, ExamQuestionScoreSituationObject> map = new HashMap<>();
        for (ExamQuestionScoreSituationObject obj : objList) {
            map.put(obj.getQuestionId(), obj);
        }
        return map;
    }
}
